package ua.com.globallogic.basecamp.krasnyanskiy.anagrams;

import java.util.*;

public class AnagramFinder {
    public Set<Anagram> findAnagrams(List<String> words) {
        Set<Anagram> result = new HashSet<Anagram>();
        Anagram anagram;

        for (String keyword : words) {
            anagram = new Anagram();
            for (String value : words) {
                if (checkForAnagram(keyword, value)) {
                    anagram.words.add(keyword);
                    anagram.words.add(value);
                    words.set(words.indexOf(value), "");
                }
            }
            if (anagram.words.size() > 0) {
                result.add(anagram);
            }
        }
        return result;
    }

    private boolean checkForAnagram(String wordOne, String wordTwo) {
        if (wordOne.length() != wordTwo.length()) {
            return false;
        }
        if (wordOne.equals(wordTwo)) {
            return false;
        }

        char[] chars1 = wordOne.toCharArray();
        char[] chars2 = wordTwo.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        return Arrays.equals(chars1, chars2);
    }
}
